<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>心理评估 - 贵州省先进计算全省重点实验室</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/assessment.css' %}">
</head>
<body>
<style>
/* CSS 变量定义 - 添加到文件顶部 */
:root {
    --primary-color: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --secondary-color: #64748b;
    --success-color: #667eea;
    --warning-color: #f59e0b;
    --error-color: #ef4444;
    --text-color: #1f2937;
    --text-secondary: #6b7280;
    --background-color: #f8fafc;
    --border-color: #e5e7eb;
    --shadow-color: rgba(0, 0, 0, 0.1);
}

/* 行动按钮组 */
.action-buttons {
    margin-top: 20px;
    text-align: center;
}

.btn-outline {
    background: transparent;
    border: 2px solid var(--secondary-color);
    color: var(--primary-color);
    padding: 12px 24px;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-outline:hover {
    background: var(--primary-color);
    color: white;
    transform: translateY(-2px);
}

/* 模态框样式 */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
}

.modal-content {
    background: white;
    margin: 2% auto;
    padding: 0;
    border-radius: 16px;
    width: 90%;
    max-width: 1000px;
    max-height: 90vh;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(-30px) scale(0.95);
    }
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}

.modal-header {
    background: linear-gradient(135deg, var(--primary-color) 0%, #667eea 100%);
    color: white;
    padding: 20px 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h2 {
    margin: 0;
    font-size: 24px;
}

.modal-close {
    background: none;
    border: none;
    color: white;
    cursor: pointer;
    padding: 5px;
    border-radius: 4px;
    transition: background 0.3s ease;
}

.modal-close:hover {
    background: rgba(255, 255, 255, 0.2);
}

.modal-body {
    padding: 30px;
    max-height: calc(90vh - 120px);
    overflow-y: auto;
}

/* 筛选区域 */
.history-filters {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    background: #f8fafc;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 25px;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.filter-group label {
    font-weight: 600;
    color: #374151;
    font-size: 14px;
}

.filter-group select {
    padding: 10px 12px;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.3s ease;
}

.filter-group select:focus {
    outline: none;
    border-color: var(--primary-color);
}

/* 历史记录列表 */
.history-list {
    min-height: 300px;
}

.history-loading {
    text-align: center;
    padding: 50px;
    color: #6b7280;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f4f6;
    border-top: 4px solid var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 15px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.history-item {
    background: white;
    border: 2px solid #f1f5f9;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 15px;
    transition: all 0.3s ease;
}

.history-item:hover {
    border-color: var(--primary-color);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.history-item-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
}

.history-item-title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 5px 0;
}

.history-item-meta {
    display: flex;
    gap: 15px;
    font-size: 14px;
    color: #6b7280;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-completed {
    background: #dcfce7;
    color: #166534;
}

.status-incomplete {
    background: #fef3c7;
    color: #92400e;
}

.history-item-actions {
    display: flex;
    gap: 10px;
    margin-top: 15px;
}

.btn-sm {
    padding: 8px 16px;
    font-size: 14px;
    border-radius: 6px;
}

/* 分页样式 */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e5e7eb;
}

#pagination-info {
    font-size: 14px;
    color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .modal-content {
        width: 95%;
        margin: 5% auto;
    }

    .modal-body {
        padding: 20px;
    }

    .history-filters {
        grid-template-columns: 1fr;
    }

    .history-item-header {
        flex-direction: column;
        gap: 10px;
    }

    .history-item-meta {
        flex-direction: column;
        gap: 5px;
    }
}
</style>


<div class="header">
    <div class="header-content">
        <div class="logo">心理评估中心</div>
        <h1>贵州省先进计算全省重点实验室</h1>
        <button class="back-button" onclick="window.location.href='/index'">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M19 12H5M12 19L5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                      stroke-linejoin="round"/>
            </svg>
            返回首页
        </button>
    </div>
</div>

<div class="main-container">
    <div class="page-title">
        <h1>📊 相关问卷</h1>
        <p>了解自己的心理状态，开启心理健康之旅</p>
        <!-- 新增：历史查询按钮 -->
        <div class="action-buttons">
            <button class="btn btn-outline" onclick="showHistoryModal()">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M12 8V12L15 15M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
                          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                历史问卷查询
            </button>
        </div>
    </div>


    <div id="questionnaire-list">
        <div class="questionnaire-grid">
            <!-- 问卷卡片将通过JavaScript动态生成 -->
            <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #718096;">
                <div id="loading-message">🔄 正在加载问卷列表...</div>
                <div id="empty-message" style="display: none;">📝 暂无可用问卷</div>
            </div>
        </div>
    </div>

    <!-- 问卷填写表单 -->
    <div id="questionnaire-form" class="questionnaire-form">
        <div class="progress-bar">
            <div class="progress-fill" id="progress-fill" style="width: 0%"></div>
        </div>

        <div class="form-header">
            <h2 class="form-title" id="form-title">问卷标题</h2>
            <p class="form-subtitle" id="form-subtitle">问卷描述</p>
        </div>

        <div id="questions-container">
            <!-- 问题将通过JavaScript动态生成 -->
        </div>

        <div class="form-actions">
            <button class="btn btn-secondary" onclick="goBackToList_list()">返回列表</button>
            <button class="btn btn-primary" onclick="submitQuestionnaire()">提交问卷</button>
        </div>
    </div>
</div>

<div id="history-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 style="color: black">📋 历史问卷记录</h2>
            <button class="modal-close" onclick="closeHistoryModal()">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <path d="M6 6L18 18M6 18L18 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </button>
        </div>

        <div class="modal-body">
            <!-- 搜索和筛选区域 -->
            <div class="history-filters">
                <div class="filter-group">
                    <label>时间范围：</label>
                    <select id="time-filter">
                        <option value="">全部时间</option>
                        <option value="7">近7天</option>
                        <option value="30">近30天</option>
                        <option value="90">近90天</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>问卷类型：</label>
                    <select id="type-filter">
                        <option value="">全部类型</option>
                        <!-- 动态加载问卷类型 -->
                    </select>
                </div>
{#                <div class="filter-group">#}
{#                    <label>完成状态：</label>#}
{#                    <select id="status-filter">#}
{#                        <option value="">全部状态</option>#}
{#                        <option value="completed">已完成</option>#}
{#                        <option value="incomplete">未完成</option>#}
{#                    </select>#}
{#                </div>#}
                <button class="btn btn-primary btn-sm" style="width: 60%;margin-left: 60px;" onclick="searchHistory()">🔍 搜索</button>
            </div>

            <!-- 历史记录列表 -->
            <div id="history-list" class="history-list">
                <div class="history-loading">
                    <div class="loading-spinner"></div>
                    <p>正在加载历史记录...</p>
                </div>
            </div>

            <!-- 分页控制 -->
            <div id="history-pagination" class="pagination" style="display: none;">
                <button class="btn btn-sm" onclick="loadHistoryPage('prev')">上一页</button>
                <span id="pagination-info">第 1 页，共 1 页</span>
                <button class="btn btn-sm" onclick="loadHistoryPage('next')">下一页</button>
            </div>
        </div>
    </div>
</div>

<div class="footer">
    © 2025 贵州省先进计算全省重点实验室 版权所有
</div>

{% load static %}
<script src="{% static 'js/assessment.js' %}"></script>
<script>
// 历史查询相关变量
let currentHistoryPage = 1;
let totalHistoryPages = 1;
let currentFilters = {
    timeRange: 1000,
    questionnaireType: '',
    status: ''
};

// 显示历史查询模态框
function showHistoryModal() {
    document.getElementById('history-modal').style.display = 'block';
    document.body.style.overflow = 'hidden'; // 防止背景滚动
    loadHistoryData();
    {#loadQuestionnaireTypes(); // 加载问卷类型选项#}
}

// 关闭历史查询模态框
function closeHistoryModal() {
    document.getElementById('history-modal').style.display = 'none';
    document.body.style.overflow = 'auto';
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modal = document.getElementById('history-modal');
    if (event.target === modal) {
        closeHistoryModal();
    }
}

// 加载问卷类型选项
async function loadQuestionnaireTypes() {
    try {
        const response = await fetch('/api/questionnaire/types/', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        if (response.ok) {
            const data = await response.json();
            const typeFilter = document.getElementById('type-filter');

            // 清空现有选项（保留"全部类型"）
            while (typeFilter.children.length > 1) {
                typeFilter.removeChild(typeFilter.lastChild);
            }

            // 添加问卷类型选项
            data.types.forEach(type => {
                const option = document.createElement('option');
                option.value = type.id;
                option.textContent = type.name;
                typeFilter.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载问卷类型失败:', error);
    }
}

// 加载历史数据
async function loadHistoryData(page = 1) {
    const historyList = document.getElementById('history-list');
    const pagination = document.getElementById('history-pagination');

    // 显示加载状态
    historyList.innerHTML = `
        <div class="history-loading">
            <div class="loading-spinner"></div>
            <p>正在加载历史记录...</p>
        </div>
    `;
    pagination.style.display = 'none';

    try {
        const params = new URLSearchParams({
            page: page,
            page_size: 10,
            ...currentFilters
        });

        const response = await fetch(`/api/report_history/?${params}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        if (response.ok) {
            const data = await response.json();
            renderHistoryList(data.results);
            updatePagination(data.count, page, data.page_size);
        } else {
            throw new Error('获取历史数据失败');
        }
    } catch (error) {
        console.error('加载历史数据失败:', error);
        historyList.innerHTML = `
            <div class="history-loading">
                <p style="color: #ef4444;">❌ 加载历史记录失败，请稍后重试</p>
            </div>
        `;
    }
}

// 渲染历史记录列表
function renderHistoryList(historyData) {
    const historyList = document.getElementById('history-list');

    if (historyData.length === 0) {
        historyList.innerHTML = `
            <div class="history-loading">
                <p style="color: black">📝 暂无符合条件的历史记录</p>
            </div>
        `;
        return;
    }

    const historyHTML = historyData.map(item => `
        <div class="history-item">
            <div class="history-item-header">
                <div>
                    <h3 class="history-item-title">${item.questionnaire_title}</h3>
                    <div class="history-item-meta">
                        <span>📅 ${formatDate(item.created_at)}</span>


                    </div>
                </div>
                <span class="status-badge ${item.status === 'completed' ? 'status-completed' : 'status-incomplete'}">
                    ${item.status === 'completed' ? '✅ 已完成' : '⏳ 未完成'}
                </span>
            </div>

            ${item.status === 'completed' ? `
                <div class="history-item-actions">
                    <button class="btn btn-primary btn-sm" onclick="downloadHistoryReport(${item.questionnaire_id})">
                        📊 下载报告
                    </button>
                    ${item.allow_retake ? `
                        <button class="btn btn-outline btn-sm" onclick="retakeQuestionnaire(${item.questionnaire_id})">
                            🔄 重新测试
                        </button>
                    ` : ''}
                </div>
            ` : `
                <div class="history-item-actions">
                    <button class="btn btn-primary btn-sm" onclick="continueQuestionnaire(${item.id})">
                        ▶️ 继续填写
                    </button>
                    <button class="btn btn-secondary btn-sm" onclick="deleteHistoryItem(${item.id})">
                        🗑️ 删除记录
                    </button>
                </div>
            `}
        </div>
    `).join('');

    historyList.innerHTML = historyHTML;
}

// 更新分页信息
function updatePagination(totalCount, currentPage, pageSize) {
    totalHistoryPages = Math.ceil(totalCount / pageSize);
    currentHistoryPage = currentPage;

    const pagination = document.getElementById('history-pagination');
    const paginationInfo = document.getElementById('pagination-info');

    if (totalHistoryPages > 1) {
        pagination.style.display = 'flex';
        paginationInfo.textContent = `第 ${currentPage} 页，共 ${totalHistoryPages} 页 (总计 ${totalCount} 条记录)`;

        // 更新按钮状态
        const prevBtn = pagination.querySelector('button:first-child');
        const nextBtn = pagination.querySelector('button:last-child');

        prevBtn.disabled = currentPage <= 1;
        nextBtn.disabled = currentPage >= totalHistoryPages;
    } else {
        pagination.style.display = 'none';
    }
}

// 搜索历史记录
function searchHistory() {
    currentFilters = {
        timeRange: Number((document.getElementById('time-filter').value || "").trim() || 1000),
        questionnaireType: document.getElementById('type-filter').value,
    };

    currentHistoryPage = 1;
    loadHistoryData(1);
}

// 翻页功能
function loadHistoryPage(direction) {
    let newPage = currentHistoryPage;

    if (direction === 'prev' && currentHistoryPage > 1) {
        newPage = currentHistoryPage - 1;
    } else if (direction === 'next' && currentHistoryPage < totalHistoryPages) {
        newPage = currentHistoryPage + 1;
    }

    if (newPage !== currentHistoryPage) {
        loadHistoryData(newPage);
    }
}

// 查看历史结果
async function viewHistoryResult(historyId) {
    try {
        const response = await fetch(`/api/questionnaire/history/${historyId}/result/`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        if (response.ok) {
            const data = await response.json();
            // 这里可以跳转到结果页面或者在当前页面显示结果
            window.location.href = `/assessment/result/${historyId}/`;
        } else {
            alert('获取结果失败，请稍后重试');
        }
    } catch (error) {
        console.error('查看历史结果失败:', error);
        alert('获取结果失败，请稍后重试');
    }
}

// 下载历史报告
async function downloadHistoryReport(historyId) {
    try {
        const params = new URLSearchParams({
            history_id: historyId,
        });
        const response = await fetch(`/api/report_download/?${params}`, {
            method: 'GET',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = `心理评估报告_${historyId}.docx`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } else {
            alert('下载失败，请稍后重试');
        }
    } catch (error) {
        console.error('下载报告失败:', error);
        alert('下载失败，请稍后重试');
    }
}

// 重新测试
function retakeQuestionnaire(questionnaireId) {
    if (confirm('确定要重新开始这个测试吗？之前的记录将会保留。')) {
        window.location.href = `/assessment/questionnaire/${questionnaireId}/`;
    }
}

// 继续填写
function continueQuestionnaire(historyId) {
    window.location.href = `/assessment/continue/${historyId}/`;
}

// 删除历史记录
async function deleteHistoryItem(historyId) {
    if (!confirm('确定要删除这条记录吗？删除后无法恢复。')) {
        return;
    }

    try {
        const response = await fetch(`/api/questionnaire/history/${historyId}/`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        });

        if (response.ok) {
            alert('删除成功');
            loadHistoryData(currentHistoryPage); // 重新加载当前页面
        } else {
            alert('删除失败，请稍后重试');
        }
    } catch (error) {
        console.error('删除历史记录失败:', error);
        alert('删除失败，请稍后重试');
    }
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
</body>
</html>